package com.detail;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSONObject;
import com.common.api.RouterPath;
import com.common.pojo.app.BkkpPojo;
import com.common.pojo.app.UserInfoPojo;
import com.common.pojo.bkkp.AnalysisPojo;
import com.common.pojo.detail.Record;
import com.common.pojo.detail.RecordGroup;
import com.common.pojo.dto.Result;
import com.common.utils.Constants;
import com.common.utils.ConstantsUrl;
import com.detail.adapter.RecordGroupAdapter;
import com.detail.databinding.DetailBinding;
import com.google.android.material.tabs.TabLayout;
import com.scwang.smart.refresh.footer.BallPulseFooter;
import com.scwang.smart.refresh.header.BezierRadarHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import okhttp3.Call;

@Route(path = RouterPath.DETAIL_MAIN)
public class DetailFragment extends Fragment {

    private DetailBinding detailBinding;
    private RecyclerView rvRecords;
    private RecordGroupAdapter adapter;
    private List<Record> allRecords = new ArrayList<>();
    private List<RecordGroup> groupedRecords = new ArrayList<>();
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);

    private TextView tvIncome, tvExpense, tvBalance;
    private EditText etStartDate, etEndDate;
    private Date selectedStartDate = null;
    private Date selectedEndDate = null;
    private int currentTypeFilter = 0; // 0:全部 1:收入 2:支出
    private UserInfoPojo userInfoPojo;
    private Integer limit = 10;
    private Integer offset = 0;
    private SmartRefreshLayout smartRefreshLayout;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        detailBinding = DetailBinding.inflate(inflater, container, false);

        initViews();
        initRecyclerView();
        String beginTime = null;
        if (selectedStartDate != null) {
            beginTime = sdf.format(selectedStartDate);
        }
        String endTime = null;
        if (selectedEndDate != null) {
            endTime = sdf.format(selectedEndDate);
        }
        initData(beginTime, endTime, currentTypeFilter, limit, offset);
        initFilterTabs();
        initDatePicker();
        //设置刷新逻辑
        setRefresh();
        // Inflate the layout for this fragment
        return detailBinding.getRoot();
    }

    private void initViews() {
        tvIncome = detailBinding.tvIncome;
        tvExpense = detailBinding.tvExpense;
        tvBalance = detailBinding.tvBalance;
        etStartDate = detailBinding.etStartDate;
        etEndDate = detailBinding.etEndDate;

        userInfoPojo = JSONObject.parseObject(Constants.userInfo, UserInfoPojo.class);

        // 长按可以清除文本
        etStartDate.setOnLongClickListener(v -> {
            etStartDate.setText("");
            selectedStartDate = null;
            return true;
        });

        etEndDate.setOnLongClickListener(v -> {
            etEndDate.setText("");
            selectedEndDate = null;
            return true;
        });
    }

    private void initRecyclerView() {
        smartRefreshLayout = detailBinding.smartRefreshLayout;
        rvRecords = detailBinding.rvRecords;
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        rvRecords.setLayoutManager(layoutManager);
        // 设置固定大小优化性能
        rvRecords.setHasFixedSize(true);
        adapter = new RecordGroupAdapter(groupedRecords);
        rvRecords.setAdapter(adapter);

    }


    private void initFilterTabs() {
        TabLayout tabFilter = detailBinding.tabFilter;
        tabFilter.addTab(tabFilter.newTab().setText("全部"));
        tabFilter.addTab(tabFilter.newTab().setText("收入"));
        tabFilter.addTab(tabFilter.newTab().setText("支出"));

        tabFilter.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                currentTypeFilter = tab.getPosition();
                // 0:全部 1:收入 2:支出
                //这里应该去查询,切换后分页查询还原
                limit = 10;
                offset = 0;
                String beginTime = null;
                if (selectedStartDate != null) {
                    beginTime = sdf.format(selectedStartDate);
                }
                String endTime = null;
                if (selectedEndDate != null) {
                    endTime = sdf.format(selectedEndDate);
                }
                initData(beginTime, endTime, currentTypeFilter, limit, offset);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    private void initDatePicker() {
        etStartDate.setOnClickListener(v -> showDatePicker(true));
        etEndDate.setOnClickListener(v -> showDatePicker(false));
        detailBinding.btnFilterDate.setOnClickListener(v -> {
            //筛选也应该去 查询
            String beginTime = null;
            if (selectedStartDate != null) {
                beginTime = sdf.format(selectedStartDate);
            }
            String endTime = null;
            if (selectedEndDate != null) {
                endTime = sdf.format(selectedEndDate);
            }
            limit = 10;
            offset = 0;
            initData(beginTime, endTime, currentTypeFilter, limit, offset);
        });
    }

    private void showDatePicker(boolean isStart) {
        Calendar calendar = Calendar.getInstance();
        if (isStart && selectedStartDate != null) calendar.setTime(selectedStartDate);
        if (!isStart && selectedEndDate != null) calendar.setTime(selectedEndDate);

        DatePickerDialog dialog = new DatePickerDialog(getContext(),
                (view, year, month, dayOfMonth) -> {
                    Calendar selected = Calendar.getInstance();
                    selected.set(year, month, dayOfMonth);
                    Date date = selected.getTime();

                    if (isStart) {
                        selectedStartDate = date;
                        etStartDate.setText(sdf.format(date));
                    } else {
                        selectedEndDate = date;
                        if (selectedStartDate != null && date.before(selectedStartDate)) {
                            showToast("结束日期不能早于开始日期");
                            selectedEndDate = null;
                            etEndDate.setText("");
                            return;
                        }
                        etEndDate.setText(sdf.format(date));
                    }
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
        );
        dialog.show();
    }

    // 按日期分组并筛选记录
    private void updateGroupedRecords() {
        groupedRecords.clear();

        // 先筛选符合条件的记录
        List<Record> filteredRecords = new ArrayList<>();
        for (Record record : allRecords) {
            filteredRecords.add(record);
        }

        // 按日期分组
        Map<String, RecordGroup> groupMap = new HashMap<>();
        for (Record record : filteredRecords) {
            String dateKey = sdf.format(record.getDate());
            if (!groupMap.containsKey(dateKey)) {
                Calendar cal = Calendar.getInstance();
                cal.setTime(record.getDate());
                cal.set(Calendar.HOUR_OF_DAY, 0);
                cal.set(Calendar.MINUTE, 0);
                cal.set(Calendar.SECOND, 0);
                cal.set(Calendar.MILLISECOND, 0);
                groupMap.put(dateKey, new RecordGroup(cal.getTime()));
            }
            groupMap.get(dateKey).addRecord(record);
        }

        // 转换为列表并排序
        groupedRecords.addAll(groupMap.values());
        Collections.sort(groupedRecords, Comparator.comparing(RecordGroup::getDate).reversed());

        adapter.notifyDataSetChanged();
        if (filteredRecords.isEmpty()) {
            showToast("暂无记录");
        }
    }

    private void updateStatistics(AnalysisPojo analysisPojo) {
        if (isAdded() && getView() != null) { // 双重校验（可选）
            double balance = analysisPojo.getSurplus();

            tvIncome.setText(String.format("¥%.2f", analysisPojo.getIncome()));
            tvExpense.setText(String.format("¥%.2f", analysisPojo.getNsume()));
            tvBalance.setText(String.format("¥%.2f", balance));
            tvBalance.setTextColor(balance >= 0
                    ? Color.parseColor("#2196F3")
                    : Color.parseColor("#E12F2F"));
        }
    }

    private void initData(String beginTime, String endTime, Integer type, Integer limit, Integer offset) {
        allRecords.clear();
        Map<String, String> map = new HashMap<>();
        if (userInfoPojo.getId() != null) {
            map.put("userId", userInfoPojo.getId().toString());
        }
        if (beginTime != null) {
            map.put("beginTime", beginTime);
        }
        if (endTime != null) {
            map.put("endTime", endTime);
        }
        map.put("limit", String.valueOf(limit));
        map.put("offset", String.valueOf(offset));
        map.put("type", String.valueOf(type));

        OkHttpUtils.get()
                .url(ConstantsUrl.bkkpListUrl)
                .params(map)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (e instanceof java.net.SocketTimeoutException) {
                            showToast("网络连接超时，请检查网络设置");
                        } else if (e instanceof java.io.IOException) {
                            showToast("网络请求失败，请检查网络连接");
                        } else {
                            showToast("网络请求出现未知错误");
                        }
                    }

                    @RequiresApi(api = Build.VERSION_CODES.O)
                    @Override
                    public void onResponse(String response, int id) {
                        Result result = null;
                        try {
                            result = JSONObject.parseObject(response, Result.class);
                        } catch (Exception e) {
                        }
                        if (result == null) {
                            result = Result.fail("请求返回失败");
                        }
                        if (result.getSuccess()) {

                            Object data = result.getData();
                            JSONObject jsonObject = JSONObject.parseObject(data.toString());
                            Object total = jsonObject.get("total");
                            Object dataList = jsonObject.get("data");
                            List<BkkpPojo> bkkpPojos = JSONObject.parseArray(dataList.toString(), BkkpPojo.class);
                            AnalysisPojo analysisPojo = JSONObject.parseObject(total.toString(), AnalysisPojo.class);
                            updateStatistics(analysisPojo);
                            for (BkkpPojo bkkpPojo : bkkpPojos) {
                                if (bkkpPojo.getType() == 1) {
                                    //收入
                                    allRecords.add(new Record(bkkpPojo.getId(), Record.Type.INCOME, bkkpPojo.getCategory(), bkkpPojo.getAmount(), bkkpPojo.getDate(), bkkpPojo.getRemark()));
                                } else {
                                    //支出
                                    allRecords.add(new Record(bkkpPojo.getId(), Record.Type.EXPENSE, bkkpPojo.getCategory(), bkkpPojo.getAmount(), bkkpPojo.getDate(), bkkpPojo.getRemark()));
                                }
                            }
                            if (isAdded() && getView() != null) { // 双重校验（可选）
                                updateGroupedRecords();
                            }
                        } else {
                            showToast(result.getMessage());
                        }
                    }
                });
    }

    private void showToast(String content) {
        requireActivity().runOnUiThread(() -> {
            if (isAdded() && getView() != null) { // 双重校验（可选）
                Toast.makeText(requireContext(), content, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /*
     * 设置刷新的方法
     * */
    private void setRefresh() {

        //设置头部刷新的样式
        smartRefreshLayout.setRefreshHeader(new BezierRadarHeader(getContext()));
        //设置页脚刷新的样式
        smartRefreshLayout.setRefreshFooter(new BallPulseFooter(getContext()));
        //设置头部刷新时间监听
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                smartRefreshLayout.finishRefresh(1000/*,false*/);//传入false表示刷新失败
                //添加一条新数据，再最开头的位置
                String beginTime = null;
                if (selectedStartDate != null) {
                    beginTime = sdf.format(selectedStartDate);
                }
                String endTime = null;
                if (selectedEndDate != null) {
                    endTime = sdf.format(selectedEndDate);
                }
                limit = 10;
                offset = 0;
                initData(beginTime, endTime, currentTypeFilter, limit, offset);
            }
        });
        /**
         * 上拉加载更多-
         */

        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                smartRefreshLayout.finishLoadMore(999);///延迟999毫秒后结束刷新
                offset = offset + limit;

                String beginTime = null;
                if (selectedStartDate != null) {
                    beginTime = sdf.format(selectedStartDate);
                }
                String endTime = null;
                if (selectedEndDate != null) {
                    endTime = sdf.format(selectedEndDate);
                }


                Map<String, String> map = new HashMap<>();
                if (userInfoPojo.getId() != null) {
                    map.put("userId", userInfoPojo.getId().toString());
                }
                if (beginTime != null) {
                    map.put("beginTime", beginTime);
                }
                if (endTime != null) {
                    map.put("endTime", endTime);
                }
                map.put("limit", String.valueOf(limit));
                map.put("offset", String.valueOf(offset));
                map.put("type", String.valueOf(currentTypeFilter));
                OkHttpUtils.get()
                        .url(ConstantsUrl.bkkpListUrl)
                        .params(map)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                if (e instanceof java.net.SocketTimeoutException) {
                                    showToast("网络连接超时，请检查网络设置");
                                } else if (e instanceof java.io.IOException) {
                                    showToast("网络请求失败，请检查网络连接");
                                } else {
                                    showToast("网络请求出现未知错误");
                                }
                            }

                            @RequiresApi(api = Build.VERSION_CODES.O)
                            @Override
                            public void onResponse(String response, int id) {
                                Result result = null;
                                try {
                                    result = JSONObject.parseObject(response, Result.class);
                                } catch (Exception e) {
                                }
                                if (result == null) {
                                    result = Result.fail("请求返回失败");
                                }
                                if (result.getSuccess()) {

                                    Object data = result.getData();
                                    JSONObject jsonObject = JSONObject.parseObject(data.toString());
                                    Object dataList = jsonObject.get("data");
                                    List<BkkpPojo> bkkpPojos = JSONObject.parseArray(dataList.toString(), BkkpPojo.class);

                                    if (bkkpPojos.size() == 0) {
                                        smartRefreshLayout.finishLoadMore(true);
                                        showToast("到底了");
                                        return;
                                    }

                                    smartRefreshLayout.finishLoadMore(true);
                                    //添加一条新数据，再最后的位置
                                    for (int i = 0; i < bkkpPojos.size(); i++) {
                                        if (bkkpPojos.get(i).getType() == 1) {
                                            //收入
                                            allRecords.add(allRecords.size(),
                                                    new Record(bkkpPojos.get(i).getId(), Record.Type.INCOME, bkkpPojos.get(i).getCategory(), bkkpPojos.get(i).getAmount(), bkkpPojos.get(i).getDate(), bkkpPojos.get(i).getRemark()));
                                        } else {
                                            //支出
                                            allRecords.add(allRecords.size(),
                                                    new Record(bkkpPojos.get(i).getId(), Record.Type.EXPENSE, bkkpPojos.get(i).getCategory(), bkkpPojos.get(i).getAmount(), bkkpPojos.get(i).getDate(), bkkpPojos.get(i).getRemark()));
                                        }
                                    }
                                    if (isAdded() && getView() != null) { // 双重校验（可选）
                                        updateGroupedRecords();
                                    }
                                } else {
                                    showToast(result.getMessage());
                                }
                            }
                        });


            }
        });

    }
}